package edu.sctu.yueding.adapter;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import edu.sctu.yueding.R;
import edu.sctu.yueding.activitys.OpenCameraActivity;
import edu.sctu.yueding.activitys.PhotoActivity;
import edu.sctu.yueding.utils.ImageLoader;
import edu.sctu.yueding.utils.JumpUtils;

public class PhotoGridViewAdapter extends BaseAdapter {
    private Context context;
    private String mDirPath;
    private List<String> mImgPasths;
    private LayoutInflater mInflater;
    private Boolean is_create_team_flag = false;

    // 要申请的权限
    private String[] permissions = {Manifest.permission.CAMERA};

    private int mScreenWidth;

    //回掉 选中图片路径接口
    private PhotoActivity.GetSelectedPhotoPath getSelectedPhotoPath;

    private static Set<String> mSelectedImg = new HashSet<String>();


    public PhotoGridViewAdapter(Context context, List<String> mDatas, String dirPath, Boolean is_create_team_flag) {
        this.mDirPath = dirPath;
        this.context = context;
        this.mImgPasths = mDatas;
        this.is_create_team_flag = is_create_team_flag;
        mInflater = LayoutInflater.from(context);
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        mScreenWidth = outMetrics.widthPixels;
        /**
         * 解决  activity为不可见时 选中图片清空
         */
        mSelectedImg = new HashSet<String>();
    }

    public void setGetSelectedPhotoPath(PhotoActivity.GetSelectedPhotoPath getSelectedPhotoPath) {
        this.getSelectedPhotoPath = getSelectedPhotoPath;
        getSelectedPhotoPath();
    }

    /**
     * 设置接口回调
     */
    private void getSelectedPhotoPath() {
        if (getSelectedPhotoPath != null) {
            getSelectedPhotoPath.getSelectedPhotoPath(mSelectedImg);
        }
    }

    @Override
    public int getCount() {
        if (mImgPasths != null && mImgPasths.size() > 0) {
            return mImgPasths.size() + 1;//第一个item需要显示 拍照相机
        } else {
            return 0;
        }

    }

    @Override
    public Object getItem(int position) {
        return mImgPasths.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder viewHolder;
        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.photo_item_grid_view, parent, false);
            viewHolder = new ViewHolder();

            viewHolder.mImg = (ImageView) convertView.findViewById(R.id.id_item_image);
            viewHolder.mSelect = (ImageButton) convertView.findViewById(R.id.id_item_select);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        if (position == 0) {
            viewHolder.mImg.setImageResource(R.drawable.photo_photograph);
            viewHolder.mSelect.setImageBitmap(null);
            viewHolder.mImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("flag_open_camera", is_create_team_flag);

                    Activity activity = (Activity) context;

                    // 检查该权限是否已经获取
                    int i = ContextCompat.checkSelfPermission(activity, permissions[0]);
                    // 权限是否已经 授权 GRANTED---授权  DINIED---拒绝
                    if (i != PackageManager.PERMISSION_GRANTED) {
                        // 如果没有授予该权限，就去提示用户请求

                        ActivityCompat.requestPermissions(activity, permissions, 321);

                    } else {
                        JumpUtils.jumpActivity(context, OpenCameraActivity.class, bundle);
                        activity.finish();
                    }


                }
            });
        } else {
            //重置状态
            viewHolder.mImg.setImageResource(R.drawable.photo_pictures_no);
            viewHolder.mSelect.setImageResource(R.drawable.photo_picture_unselected);
            viewHolder.mImg.setColorFilter(null);

            viewHolder.mImg.setMaxWidth(mScreenWidth / 3);

            ImageLoader.getInstance(3, ImageLoader.Type.LIFO).loadImage(mDirPath + "/" + mImgPasths.get(position - 1), viewHolder.mImg, false);

            //设置图片点击事件

            final String filePath = mDirPath + "/" + mImgPasths.get(position - 1);

            viewHolder.mImg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //已经被选择
                    if (mSelectedImg.contains(filePath)) {
                        mSelectedImg.remove(filePath);
                        viewHolder.mImg.setColorFilter(null);
                        viewHolder.mSelect.setImageResource(R.drawable.photo_picture_unselected);
                    } else {//未被选择
                        mSelectedImg.add(filePath);
                        viewHolder.mImg.setColorFilter(Color.parseColor("#77000000"));
                        viewHolder.mSelect.setImageResource(R.drawable.photo_pictures_selected);
                    }
//                notifyDataSetChanged();
                }
            });
            /**
             * 显示点击过后已保存的状态
             */
            if (mSelectedImg.contains(filePath)) {
                viewHolder.mImg.setColorFilter(Color.parseColor("#77000000"));
                viewHolder.mSelect.setImageResource(R.drawable.photo_pictures_selected);
            }

        }


        return convertView;
    }

    private class ViewHolder {
        ImageView mImg;
        ImageButton mSelect;
    }
}